package com.zzyl.nursing.service.member.Impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.mapper.member.ReservationMapper;
import com.zzyl.nursing.service.member.IReservationService;
import com.zzyl.nursing.vo.ReservationVO;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 预约信息Service业务层处理
 *
 * @author alexis
 * @date 2025-09-21
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id) {

        return reservationMapper.selectById(id);
    }

    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation) {
        reservation.setStatus(0);
        reservation.setCreateTime(new Date());
        reservation.setUpdateTime(new Date());
        Long userId = UserThreadLocal.getUserId();
        reservation.setCreateBy(userId+"");
        return reservationMapper.insert(reservation);
    }

    /**
     * 修改预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return reservationMapper.updateById(reservation);
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
        return reservationMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
        return reservationMapper.deleteById(id);
    }


    /**
     * 2.1 查询当天取消预约数量
     *
     * @param userId
     */
    @Override
    public void getCancelledReservationCount(Long userId) {
        long time = System.currentTimeMillis();
        //用于将毫秒时间戳转换为 LocalDateTime 对象。
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        //获取当天的开始时间（即凌晨00:00:00）。
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        //获取第二天的开始时间，也就是当前日期的结束时间。
        LocalDateTime endTime = startTime.plusDays(1);

        reservationMapper.getCancelledReservationCount(userId, startTime, endTime);
    }


    /**
     * 2.2 查询每个时间段剩余预约次数
     *
     * @return
     */
    @Override
    public List<ReservationVO> getCountByTime(Long userId) {
        //检查userId是否为空
        if (userId == null) {
            throw new RuntimeException("userId不能为空");
        }
        //查询每个时间段的已预约次数
        List<Map<String, Object>> result = reservationMapper.getCountByTime(userId);
        //定义每个时间段的总预约次数
        int totalReservationCount = 6;

        ArrayList<ReservationVO> reservationVO = new ArrayList<>();
        for (Map<String, Object> map : result) {
            String time = (String) map.get("time");
            String count = (String) map.get("count");

            //计算剩余次数
            int num = totalReservationCount - Integer.parseInt(count);
            ReservationVO vo = new ReservationVO(time, num);
            vo.setTime(time);
            vo.setCount(num);
            reservationVO.add(vo);
        }
        return reservationVO;
    }


    /**
     * 2.5 取消预约
     *
     * @param id
     * @param userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getCancel(Long id, Long userId) {
        // 1. 判断是否存在
      if(id==null || userId==null){
          throw new RuntimeException("id和userId不能为空");
      }
        // 2. 根据id查询预约信息
        Reservation reservation = reservationMapper.selectById(id);

        // 3. 判断是否是用户自己的预约
        if(!reservation.getCreateBy().equals(userId.toString())){
            throw new RuntimeException("不能取消别人的预约");
        }

        // 4. 只要状态为0即待报道 才能取消
        if(reservation.getStatus()!=0){
            throw new RuntimeException("只能取消待报道的预约");
        }

         // 5. 更新预约状态为已取消
        reservation.setStatus(2);
         // 将LocalDateTime转换为Date
        Date updateTime = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
        reservation.setUpdateTime(updateTime);
        // 更新预约状态为已取消
        reservationMapper.updateById(reservation);
        // 6. 保存到数据库
        reservationMapper.updateById(reservation);

    }


}
